import React, { useEffect, useRef, useState } from 'react'
import { connect } from 'react-redux'
import { Text, View, StyleSheet, Image, SafeAreaView, FlatList, TouchableOpacity, Dimensions, ActivityIndicator } from 'react-native'
import { pTx } from "../../utils/dimensions"
import { IconFill, IconOutline } from "@ant-design/icons-react-native";
import { formatFriendMsg } from "../../utils/formatFriendMsg"
import { SetFriendMsg, asyncGetFriendList } from "../../redux/features/appSlice"
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../../realm"
import Realm from "realm"
import httpApi from "../../api"
import LinearGradient from 'react-native-linear-gradient';
import Avatar from "../../components/avatar"


const getData = (friendMsgLis, friendList) => {
    let some = [];
    let MsgLis = friendMsgLis.filtered(`MT >= 40  and MT <= 42`).sorted('T', true)
    MsgLis.forEach(el => {
        if (!some.some(e => e.F == el.F)) {
            const isFriend = friendList.find(item => item.F == el.F)
            some.push({ ...el, loading: false, loading2: false, MT: isFriend ? 42 : el.MT });
        }
    });
    return some
}

const AddFriendList = ({ navigation, SetFriendMsg, asyncGetFriendList, friendApplyMsg }) => {
    const listViewRefs = useRef(null);
    const [list, setList] = useState([]);
    const realm = useRealm();
    const userInfo = useQuery(schemaName.UserInfo, userInfo => {
        return userInfo.filtered('Current = true');
    })[0];
    const friendList = useQuery(schemaName.FriendList, friend => {
        return friend.filtered(`UserId == ${userInfo.Id}`)
    })
    const friendMsgLis = useQuery(schemaName.FriendMsgLis, friend => {
        return friend.filtered(`UserId == ${userInfo.Id}`)
    })



    useEffect(() => {
        setList(getData(friendMsgLis, friendList))
    }, []);

    useEffect(() => {
        let MsgLis = friendMsgLis.filtered(`Unread == 1 and MT >= 40 `).sorted('T', true)
        console.log(MsgLis)
        realm.write(() => {
            for (const msg of MsgLis) {
                msg.Unread = 0
            }
        })
    }, [])

    const onDogsChange = (dogs, changes) => {
        changes.insertions.forEach((index) => {
            setList(getData(friendMsgLis, friendList))
        });
    }

    useEffect(() => {
        friendMsgLis.addListener(onDogsChange);
        return () => {
            friendMsgLis.removeListener(onDogsChange);
        };
    }, []);


    sendSetAddFriendStatus = async (item, id, msgType, index) => {
        try {
            setList(prev => prev.map((element, idx) => {
                if (idx === index) {
                    msgType == 42 ? element.loading2 = true : element.loading = true
                    return element
                }
                return element
            }))
            const res = await httpApi.sendFriendAddReply({ id, msgType })
            if (res.code == 20) {
                realm.write(() => {
                    realm.create(schemaName.FriendMsgLis, {
                        ...item,
                        MT: msgType,
                    }, true);
                })
                if (msgType == 42) {
                    const getFriendList = await httpApi.getFriendList()
                    var timestamp = Date.parse(new Date()) / 1000
                    realm.write(() => {
                        getFriendList.data.FriendList && getFriendList.data.FriendList.map(item => realm.create(schemaName.FriendList, { ...item, UserId: userInfo.Id, State: 1 }, true))
                        realm.create(schemaName.FriendMsgLis, {
                            F: item.F,
                            M: item.Message || '你们已经成为了好友',
                            MT: 0,
                            S: item.S,
                            T: timestamp,
                            _id: new Realm.BSON.UUID(),
                            UserId: userInfo.Id
                        }, true);
                    })
                }

            }
        } catch (error) {
        }
        setList(prev => prev.map((element, idx) => {
            if (idx === index) {
                msgType == 42 ? element.loading2 = false : element.loading = false
                element.MT = msgType
                return element
            }

            return element
        }))
    }
    useEffect(() => {
        navigation.setOptions({
            headerRight: () => (
                <TouchableOpacity style={styles.FeedbackIcon} onPress={() => navigation.navigate('addFriends')}>
                    <IconOutline style={styles.icon} name="user-add" />
                </TouchableOpacity>
            ),
        });
    }, [navigation]);
    renderItem = ({ item, index }) => {
        const { 0: id, 1: name, 2: image, 3: Message } = item.M?.split(' ')
        return (
            <View style={styles.li}>
                <View style={[styles.row, styles.flexDirectionRow]}>
                    <Avatar style={[styles.avatar]} source={{ uri: image }}></Avatar>
                    <View style={styles.cell}>
                        <Text style={styles.name} >{name || item.R}</Text>
                        {Message && <Text style={styles.txt} ellipsizeMode={'tail'} numberOfLines={1}>{Message}</Text>}
                    </View>
                </View>

                {item.MT == 40 ?
                    <View style={styles.buttonRight} >
                        <TouchableOpacity style={styles.reject} loading={item.loading} disabled={item.loading} onPress={() => this.sendSetAddFriendStatus(item, id, 41, index)}>
                            {item.loading ? <ActivityIndicator /> : <Text>拒绝</Text>}
                        </TouchableOpacity>
                        <LinearGradient
                            colors={['rgba(51, 225, 144, 1)', 'rgba(68, 225, 240, 1)']}
                            start={{ x: 0.25, y: 0.25 }}
                            end={{ x: 0.75, y: 0.75 }}
                            style={[{ borderRadius: pTx(6) }]}>
                            <TouchableOpacity style={styles.accept} loading={item.loading2} disabled={item.loading2} onPress={() => this.sendSetAddFriendStatus(item, id, 42, index)}>
                                {item.loading2 ? <ActivityIndicator /> : <Text>接受</Text>}
                            </TouchableOpacity>
                        </LinearGradient>
                    </View>
                    : item.MT == 41 ?
                        <Text style={styles.Status1} onPress={() => this.sendSetAddFriendStatus(item, id, 42, index)}>已拒绝</Text>
                        :
                        <Text style={styles.Status2} onPress={() => this.sendSetAddFriendStatus(item, id, 41, index)}>已添加</Text>
                }
            </View >
        )
    }
    return (
        <SafeAreaView style={styles.container}>
            <FlatList
                style={{ flex: 1 }}
                renderItem={this.renderItem}
                data={list}
                keyExtractor={(item, index) => item._id || index}
            />
        </SafeAreaView>
    )
}

const mapStateToProps = (state) => (state.app)

const mapDispatchToProps = {
    SetFriendMsg,
    asyncGetFriendList
}

export default connect(mapStateToProps, mapDispatchToProps)(AddFriendList)

const styles = StyleSheet.create({
    icon: {
        fontSize: pTx(20),
        color: "#0A0C14"
    },
    FeedbackIcon: {
        paddingRight: pTx(16),
    },
    flexDirectionRow: {
        flexDirection: 'row',
        justifyContent: "space-between",
        alignItems: "center",
    },

    container: {
        flex: 1,
        backgroundColor: "#fff",
    },
    li: {
        flexDirection: 'row',
        justifyContent: "space-between",
        alignItems: "center",
        paddingVertical: pTx(15),
        paddingHorizontal: pTx(12),
        borderBottomColor: "rgba(175,181,189,0.15)",
        borderBottomWidth: 1
    },
    avatar: {
        width: pTx(45),
        height: pTx(45),
        borderRadius: pTx(6),
    },
    cell: {
        marginLeft: pTx(12),
    },
    name: {
        fontSize: pTx(16),
        color: "#0A0C14"
    },
    txt: {
        marginTop: pTx(5),
        fontSize: pTx(12),
        color: "#AFB5BD",
        maxWidth: Dimensions.get('screen').width - pTx(150),
    },
    Status1: {
        fontSize: pTx(16),
        color: "#AFB5BD"
    },
    Status2: {
        fontSize: pTx(16),
        color: "#AFB5BD"
    },
    buttonRight: {
        flexDirection: 'row',
        justifyContent: "space-between",
        alignItems: "center",
    },
    reject: {
        paddingHorizontal: pTx(15),
        paddingVertical: pTx(5),
        marginRight: pTx(10),
        borderRadius: pTx(6),
        fontSize: pTx(16),
        color: "#fff",
        borderWidth: 0,
        height: pTx(30),
        backgroundColor: "#ff9d9d"
    },
    accept: {
        paddingHorizontal: pTx(15),
        paddingVertical: pTx(5),
        borderRadius: pTx(6),
        fontSize: pTx(16),
        color: "#0A0C14",
        backgroundColor: "transparent",
        borderWidth: 0,
    }
})